﻿using System;
using System.Diagnostics;

namespace ECommon
{
    /// <summary>
    /// 秒表工具
    /// </summary>
    public static partial class StopWatchTool
    {
        /// <summary>
        /// 计时条件下执行操作
        /// </summary>
        /// <param name="action">要执行的动作</param>
        /// <returns>执行时间</returns>
        public static double StopWatchRun(Action action)
        {
            CreatInstance();
            _sw.Reset();
            _sw.Start();
            action();
            _sw.Stop();
            return (_sw.ElapsedMilliseconds / 1000.0);
        }

        /// <summary>
        /// 计时条件下执行操作
        /// </summary>
        /// <typeparam name="T">参数类型1</typeparam>
        /// <typeparam name="U">参数类型2</typeparam>
        /// <typeparam name="V">返回类型</typeparam>
        /// <param name="action">要执行的动作</param>
        /// <param name="arg1">参数1</param>
        /// <param name="arg2">参数2</param>
        /// <param name="result">外传参数，返回结果</param>
        /// <returns>执行时间</returns>
        public static double StopWatchRun<T, U, V>(Func<T, U, V> action, T arg1, U arg2, out V result)
        {
            CreatInstance();
            _sw.Reset();
            _sw.Start();
            result = action(arg1, arg2);
            _sw.Stop();
            return (_sw.ElapsedMilliseconds / 1000.0);
        }
        /// <summary>
        /// 停表
        /// </summary>
        private static Stopwatch _sw = null;

        /// <summary>
        /// 单例锁定
        /// </summary>
        private static readonly string _swLock = "swLock";

        /// <summary>
        /// 锁定构建单例
        /// </summary>
        private static void CreatInstance()
        {
            if (_sw == null)
            {
                lock (_swLock)
                {
                    if (_sw == null)
                    {
                        _sw = new Stopwatch();
                    }
                }
            }
        }
    }
}
